#!/usr/bin/env python
#-*- coding:utf8 -*-
import web
import hashlib
from app.models.model import Model
from app.models.quest import Quest
from app.helpers.sites_helper import Helper
class Site(Model):
    table = 'sites'
    Quest = Quest()

    #新添加网站
    def create(self,data):
        try:
            status = self.insert(
                    uid     = data['uid'],
                    level   = data['level'],
                    name    = data['name'],
                    domain  = data['domain'],
                    host    = data['host'],
                    port    = data['port']
                    )
            if status:
                return self.Quest.create(status,1)
            return False
        except:
            return False

    #添加其他域名
    def create_by_sub(self,id,data):
        if self.insert(uid = data['uid'],fid = data['fid'],level = data['level'],domain = data['domain']):
            return self.Quest.create(id,2)
        return False

    #更新HOST
    def update_by_host(self,id,host):
        if self.save(id, host = host):
            return self.Quest.create(id,2)
        return False

    #更新其他域名信息
    def update_by_domain(self,fid,id,domain):
        if self.save(id, domain = domain):
            return self.Quest.create(fid,2)
        return False

    #更新端口
    def update_by_port(self,id,port):
        if self.save(id, port = port):
            return self.Quest.create(id,2)
        return False

    #更新CNAME
    def update_by_cname(self,id):
        if self.save(id, is_cname = 1):
            #判断队列任务中是否存在该任务
            quest = self.Quest.get_by("sid = '%s' and type = 1" % id)
            if quest is None:
                return self.Quest.create(id,2)
            else:
                return self.Quest.save(quest.id,type = 2)
        return False

    #删除其他域名
    def destory_by_sub(self,fid,id):
        if self.delete(id):
            return self.Quest.create(fid,2)
        return False

    #删除网站
    def destory(self,id):
        if self.delete(id):
            #获取该站点其他域名
            if self.count_by("fid = '%s'" % id) > 0:
                #是否删除成功
                if self.delete_by("fid = '%s'" % id) is False:
                    return False
            #获取该站点队列任务
            if self.Quest.count_by("sid = '%s'" % id) > 0:
                #是否删除成功
                if self.Quest.delete_by("sid = '%s'" % id) is False:
                    return False
            #添加队列消息删除节点网站配置信息
            return self.Quest.create(id,3)
        else:
            return True

    #获取其他域名
    def get_subs(self,id):
        subs = []
        if self.count_by("fid ='%s' and status = 1" % id):
            for sub in self.get_many_by("fid = '%s' and status = 1" % id):
                subs.append(sub.domain)
        return subs
